<?php

namespace WpOrg\Requests\Tests\Transport\Fsockopen;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Hooks;
use WpOrg\Requests\Requests;
use WpOrg\Requests\Tests\Transport\BaseTestCase;
use WpOrg\Requests\Transport\Fsockopen;

final class FsockopenTest extends BaseTestCase {
	protected $transport = Fsockopen::class;

	public function testBadIP() {
		$this->expectException(Exception::class);
		parent::testBadIP();
	}

	public function testExpiredHTTPS() {
		$this->expectException(Exception::class);
		$this->expectExceptionMessage('certificate verify failed');
		parent::testExpiredHTTPS();
	}

	public function testRevokedHTTPS() {
		$this->expectException(Exception::class);
		$this->expectExceptionMessage('certificate verify failed');
		parent::testRevokedHTTPS();
	}

	/**
	 * Test that SSL fails with a bad certificate
	 */
	public function testBadDomain() {
		$this->expectException(Exception::class);
		$this->expectExceptionMessage('SSL certificate did not match the requested domain name');
		parent::testBadDomain();
	}

	/**
	 * Issue #248.
	 */
	public function testContentLengthHeader() {
		$hooks = new Hooks();
		$hooks->register('fsockopen.after_headers', [$this, 'checkContentLengthHeader']);

		Requests::post($this->httpbin('/post'), [], [], $this->getOptions(['hooks' => $hooks]));
	}

	/**
	 * Issue #248.
	 */
	public function checkContentLengthHeader($headers) {
		$this->assertStringContainsString('Content-Length: 0', $headers);
	}

	/**
	 * Issue #335/#339.
	 */
	public function testHTTPVersionHeader() {
		// Remember the original locale.
		$locale = setlocale(LC_NUMERIC, 0);

		// Set the locale to one using commas for the decimal point.
		setlocale(LC_NUMERIC, 'de_DE@euro', 'de_DE.utf8', 'de_DE', 'de', 'ge');

		// Make sure the locale was changed.
		$this->assertNotSame($locale, setlocale(LC_NUMERIC, 0), 'Changing the locale failed');

		$hooks = new Hooks();
		$hooks->register('fsockopen.after_headers', [$this, 'checkHTTPVersionHeader']);

		Requests::post($this->httpbin('/post'), [], [], $this->getOptions(['hooks' => $hooks]));

		// Reset the locale.
		setlocale(LC_NUMERIC, $locale);
	}

	/**
	 * Issue #335/#339.
	 */
	public function checkHTTPVersionHeader($headers) {
		$this->assertStringContainsString('HTTP/1.1', $headers, 'HTTP header is influenced by the system locale');
	}
}
